<?php

/**
 * Created by PhpStorm.
 * User: jhon
 * Date: 2018/2/10
 * Time: 9:59
 *        header('Content-Type: application/json');
 */
namespace app\api\controller;
use think\controller;
use think\Validate;
use think\Request;
use think\Db;
class Common extends Auto
{
    protected $scene = [
        'edit'  =>  ['name','age'=>'require|number|between:1,120'],
    ];

    public $downpath = 'http://58.17.249.56:8900/ems_tp5_master/public/uploads/devicesoftware/';
    /**
     * @param  mac 软件版本号
     * 判断是否有升级资格 版本号 查询设备类型
     * 根据设备类别、版本号判断升级
     */
    public function upgrade(){

        $dev_mac = input('dev_mac');
        $dev_edition = input('dev_edition');

        $data = [
            'id'=>input('id'),
            'dev_mac'=>$dev_mac,
            'dev_edition'=>$dev_edition,
        ];
        $user_rule = [
            'id' => 'require',
            'dev_mac' => 'require|max:25',
            'dev_edition' => 'require|max:25',
        ];
        $validate = new Validate($user_rule);
        $result   = $validate->check($data);
        if(!$result){
            $message = $validate->getError();
            return json(returnRest($message,[],100001));
        }
        $devtype = $this->getdevtype($dev_mac);
//        var_dump($devtype);exit();
        if($devtype['status'] == 1){
            $message = '设备不存在';
            return json(returnRest($message, [], 8004));
        }else if($devtype['status'] == 2){
            $message = '设备已禁用';
            return json(returnRest($message, [], 8005));
        }
//        根据设备类型查询是否升级
        $devsoftarr = [
            'dev_type'=>$devtype['code']['dev_type'],
        ];
//        $data =$this->getdevsoftedi($devtype['code']);
        $data =$this->getdevsoftedi($devsoftarr,$dev_edition);
        $content = [
            'content'=>$data['code']
        ];

        $message =$data['message'];
        $rcode =$data['status'];
        return json(returnRest($message, $content, $rcode));
    }

    /**
     * 获取设备类型
     * @param $dev_mac
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getdevtype($dev_mac){
        try{
            $result  = Db::table('device')
                ->where('dev_mac',$dev_mac)
                ->select();
            if(!$result){
                return [
                    'status'=>1,
                    'code'=>'',
                    'message'=>'dev_mac设备不存在'
                ];
            }else{
                if($result[0]['dev_status'] ==0){
                    return [
                        'status'=>2,
                        'code'=>'',
                        'message'=>'设备已禁用'
                    ];
                }else{
                    return [
                        'status'=>0,
                        'code'=>$result[0],
                        'message'=>''
                    ];
                }

            }
        }catch (\Exception $e){
            $message= $e->getMessage();
            return returnRest($message,[],9007);
        }

    }

    /**
     * 获取设备软件版本
     * @param $dev_type
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getdevsoftedi($dev_type,$dev_edition){
        try{
            $result  = Db::table('device_software')
//                ->where('dev_type',$dev_type)
                ->where($dev_type)
                ->order('dev_edition desc')
                ->limit(1)
                ->select();
            if(!$result){
                return 'dev_type设备类型不存在';
            }else{

                $nowedition =$this->versionCompare($dev_edition,$result[0]['dev_edition']);
//                echo ($nowedition);
                switch ($nowedition){
                    case '=':

                        return [
                            'status'=>'8006',
                            'message'=>'版本相同无需升级',
                            'code'=>''
                        ];
                        break;
                    case '<':
//                        $result[0]['path'] = $this->downpath;
                        $result[0]['file_url'] = $this->downpath.str_replace('\\','/',$result[0]['file_url']);
                        return [
                            'status'=>'0',
                            'message'=>'升级',
                            'code'=>$result
                        ];
                        break;
                    case '>':
                        return [
                            'status'=>'8007',
                            'message'=>'版本过高数据库无匹配项',
                            'code'=>''
                        ];
                        break;
                }

//                return $result;
            }
        }catch (\Exception $e){
            $message= $e->getMessage();
            return json(returnRest($message,[],9007));
        }
    }


    /**
     * 对比版本
     * @param $a
     * @param $b
     * @return string
     */
    public function versionCompare($a, $b)
    {
        // a,b已存在、非空字符串或者非零
        if (empty($a) || empty($b))
            return "errmsg：不可为空。";

        // 字符串必须为用'.'隔开的数字串
        $rule = "/^\d+(\.\d+)*$/";
        $aMat = preg_match($rule, $a);
        $bMat = preg_match($rule, $b);
        if (!$aMat || !$bMat)
            return "errmsg: 必须为用'.'隔开的数字串。";

        // 移除最后的.0
        $a = explode(".", rtrim($a, ".0"));
        $b = explode(".", rtrim($b, ".0"));

        foreach ($a as $depth => $aVal)
        {
            if (isset($b[$depth])){
                if ($aVal > $b[$depth]) return '>';
                else if ($aVal < $b[$depth]) return '<';
            }else{
                return '>';
            }
        }
        return (count($a) < count($b)) ? '<' : '=';
    }


    public function padupgrade(){
        $pad_edition = input('pad_edition');
        $data = [
            'id'=>input('id'),
            'pad_edition'=>$pad_edition,
        ];
        $user_rule = [
            'id' => 'require',
            'pad_edition' => 'require|max:25',
        ];
        $validate = new Validate($user_rule);
        $result   = $validate->check($data);
        if(!$result){
            $message = $validate->getError();
            return json(returnRest($message,[],100001));
        }

        $data =$this ->getpadsoftedi($pad_edition);
//        var_dump($data);
        $content = [
            'content'=>$data['code']
        ];
        $message =$data['message'];
        $rcode =$data['status'];
        return json(returnRest($message, $content, $rcode));
    }

    /**
     * 获取版本
     * @param $dev_edition
     * @return array|\think\response\Json
     */
    public function getpadsoftedi($dev_edition){
        try{
            $result  = Db::table('pad_software')
                ->order('pad_edition desc')
                ->limit(1)
                ->select();
                $nowedition =$this->versionCompare($dev_edition,$result[0]['pad_edition']);
                switch ($nowedition){
                    case '=':
                        return [
                            'status'=>'8006',
                            'message'=>'版本相同无需升级',
                            'code'=>''
                        ];
                        break;
                    case '<':
//                        $result[0]['file_url'] = $this->downpath.str_replace('\\','/',$result[0]['file_url']);
                        return [
                            'status'=>'0',
                            'message'=>'升级',
                            'code'=>$result[0]['file_url']
                        ];
                        break;
                    case '>':
                        return [
                            'status'=>'8007',
                            'message'=>'版本过高数据库无匹配项',
                            'code'=>''
                        ];
                        break;
                }

        }catch (\Exception $e){
            $message= $e->getMessage();
            return json(returnRest($message,[],9007));
        }
    }

    /**
     * pad账号日志记录添加 修改登陆时间
     */
    public function padacclogadd(){


        try{

//            echo json_encode(input());exit();

            $create_time = date('Y-m-d H:i:s',time());
            $pad_dev_unique_id = input('pad_dev_unique_id');//pad 唯一标识
            $pad_user_id = input('pad_user_name');//用户名
            $data = [
                'id'=>input('id'),
                'pad_dev_unique_id'=>$pad_dev_unique_id,
                'pad_user_name'=>$pad_user_id,
                'create_time'=>$create_time,
            ];
            $user_rule = [
                'id' => 'require',
                'pad_dev_unique_id' => 'require|max:100',
                'pad_user_name' => 'require|max:36',
            ];
            $validate = new Validate($user_rule);
            $result   = $validate->check($data);
            if(!$result){
            $message = $validate->getError();
            return json(returnRest($message,[],100001));
        }
            unset($data['id']);

//            判断用户是否存在
            $usermark = $this->getusermark($pad_user_id,$create_time);

            if(!$usermark){
                $message = '用户不存在';
                return json(returnRest($message,[],101006));
            }
//            新增日志数据
            $data['org_code'] = $usermark[0]['org_code'];
//            var_dump($data);
            $result  = Db::table('pad_acc_status_log')->insert($data);
            if(empty($result)){
                $message = '数据库内部错误';
                return json(returnRest($message,[],9000));
            }

            $useronj = new Users();
//            修改最后一次在线时间
            $ruslt = $useronj->updonlinetime($pad_user_id,$create_time);
            if(empty($ruslt)){
                $message = '数据添加成功，修改在线时间失败';
                return json(returnRest($message,[],101007));
            }

            $message ='数据添加成功！';
            return json(returnRest($message,[],0));

        }catch (\Exception $e){
            $message= $e->getMessage();
            return json(returnRest($message,[],9000));
        }

    }

    /**
     * 判断用户是否存在
     * @param $user_name
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getusermark($user_name){

        $result  = Db::table('padaccount')
            ->where('name',$user_name)
            ->select();

        if(empty($result)){
            return false;
        }else{
            return $result;
        }



    }


    /**
     * 设备日志记录添加
     */
    public function devicelogadd(){
        try{
//            echo json_encode(input());exit();

            $create_time = date('Y-m-d H:i:s',time());
            $pad_dev_unique_id = input('pad_dev_unique_id');//pad 唯一标识
            $dev_code = input('dev_code');
            $pad_acc_name = input('pad_user_name');
            $dev_type = input('dev_type');
            $dev_status = input('dev_status');

            $data = [
                'id'=>input('id'),
                'pad_dev_unique_id'=>$pad_dev_unique_id,
                'dev_code'=>$dev_code,
                'pad_user_name'=>$pad_acc_name,
                'dev_type'=>$dev_type,
                'dev_status'=>$dev_status,
            ];
            $user_rule = [
                'id' => 'require',
                'pad_dev_unique_id' => 'require|max:100',
                'dev_code' => 'require|max:100',
                'pad_user_name' => 'require|max:36',
                'dev_type' => 'require|max:36',
                'dev_status' => 'require|max:36',
            ];
            $validate = new Validate($user_rule);
            $result   = $validate->check($data);
            if(!$result){
                $message = $validate->getError();
                return json(returnRest($message,[],100001));
            }

//            判断用户是否存在
            $usermark = $this->getusermark($pad_acc_name,$create_time);
            if(!$usermark){
                $message = '用户不存在';
                return json(returnRest($message,[],101006));
            }


//            验证设备是否正确
            $devparamarr = [
                'dev_code'=>$dev_code,
                'dev_type'=>$dev_type,
            ];
            $devmarkobj = new Device();
            $devresult = $devmarkobj->getdevicemark($devparamarr);
            if(!$devresult){
                $message = '设备不存在，或设备编码与设备类型不匹配';
                return json(returnRest($message,[],701006));
            }

//            添加设备日志
            unset($data['id']);
            $data['create_time']=date('Y-m-d H:i:s',time());
            $data['org_code'] = $usermark[0]['org_code'];
            $result  = Db::table('dev_status_log')->insert($data);
            if(!$result){
                $message = '添加设备日志失败';
                return json(returnRest($message,[],701007));
            }

            $message ='数据添加成功！';
            return json(returnRest($message,[],0));


        }catch (\Exception $e){
            $message= $e->getMessage();
            return json(returnRest($message,[],9000));
        }
    }

}